package com.example.a90419.audio;

import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.AudioTrack;
import android.media.MediaRecorder;
import android.os.AsyncTask;
import android.util.Log;

public class XFAudioRecord {

    private static final String TAG = "XFAudioRecord";

    private AudioRecord audioRecord;
    private byte[] buff = null;
    private boolean isRecording = false;
    private MyAsynTask task;
    private boolean isSaveFile = false; //是否写入文件
    private LoadStreamListener listener;
    private int messageMaxLen = 8000 * 50; //消息的最大长度  当达到这个值的时候就需要主动断开录制
    private int messagePackage = 650;  //发送消息的封包大小


    public XFAudioRecord(){
        initData();
    }


    private void initData() {
        int encoding = AudioFormat.ENCODING_PCM_16BIT; //格式
        int channel_sound = AudioFormat.CHANNEL_IN_MONO;//通道
        int frequence = 8000;//HZ
        int buffSize = AudioTrack.getMinBufferSize(frequence, channel_sound, encoding);
        Log.i(TAG, "init: 获取到的buffsize为：" + buffSize + " 推荐使用800");
        buff = new byte[buffSize];
        audioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC,
                frequence, channel_sound, encoding, buffSize);
    }


    /**
     * 开启录制
     */
    public void start() {
        isRecording = true;
        audioRecord.startRecording();
        task = new MyAsynTask();
        task.execute();
    }

    /**
     * 结束录制
     */
    public synchronized void end() {
        isRecording = false;
        audioRecord.stop();
        task = null;
    }

    /**
     * 销毁资源
     */
    public void destory() {
        if (null != audioRecord) {
            audioRecord.release();
            audioRecord = null;
        }
    }

    public void setListener(LoadStreamListener listener) {
        this.listener = listener;
    }

    private void messageBox(byte[] buffs) {
        if (null != listener) {
            int offset = buffs.length % messagePackage > 0 ? 1 : 0;
            for (int i = 0; i < buffs.length / messagePackage + offset; i++) {
                //即当获取的到（消息字节数/最大封包字节数）能整除表示分块数目够  当不能整除需要在+1个
                listener.load(buffs, i, messagePackage);
            }
        }


    }


    public interface LoadStreamListener {

        /**
         * 获取到的封包 将整个打封包拆分成小分包便于发送和降低延迟
         *
         * @param stream 整个封包的大小
         * @param offset 封包的偏移
         * @param len    单个封包的大小
         */
        void load(byte[] stream, int offset, int len);
    }

    /**
     * 执行录制任务
     */
    private class MyAsynTask extends AsyncTask<String, Integer, String> {

        private long startTime;


        //任务线程
        @Override
        protected String doInBackground(String... strings) {
            int k = 0;
            while (isRecording) {
                int result = audioRecord.read(buff, 0, buff.length);
              //  Log.e(TAG, "doInBackground: 达到了buff的最大长度：" + buff.length);
                if (isSaveFile) {
                    //todo  可以实现以文件形式保存
                }
                for (int i = 0; i < result; i++) {
                    if (k >= messageMaxLen) { //如果达到了消息的最大值 那么立即停止录制 防止一直录制
                        end();
                        return "stop";
                    }
                    publishProgress(k);
                    k++;
                }
                byte[] temp = buff;
                messageBox(temp);

            }

            return "success";
        }

        @Override
        protected void onPreExecute() {
            startTime = System.currentTimeMillis() / 1000;
        }

        @Override
        protected void onPostExecute(String s) {

            Log.e(TAG, "onPostExecute: 返回文字：" + s);
            //执行时间

            Log.i(TAG, "onPostExecute: 录制执行时间:" + (System.currentTimeMillis() / 1000 - startTime) + "s");
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            for (Integer value : values) {
                if (value >= messageMaxLen)
                    Log.e(TAG, "onProgressUpdate: 获取到的最大的字节大小为：" + value);
            }

        }

        @Override
        protected void onCancelled() {
            isRecording = false;
            audioRecord.stop();
        }
    }

}
